<?php

declare(strict_types=1);

namespace app\api\controller\v1;
use app\common\Frontend;
use app\common\model\Message as AppMessage;
use app\common\model\MessageClass;
use app\common\model\PublicStatus;
use app\common\model\ReadMessage;
use app\common\model\VipPrice;
use app\common\model\VipType;

class Message extends Frontend
{

    protected array $noNeedLogin = [];

    protected $model;
    public function initialize(): void
    {
        parent::initialize();
        $this->model = new AppMessage();
    }

       //消息类型数据源
    public function messageClassList() : void {
        $res = MessageClass::where(['status'=>PublicStatus::PUBLIC_STATUS_ONE])->select()->toArray();
        $this->success('', [
            'list'   => $res,
            'remark' => '',
        ]);
    }



    //消息数据源
    public function messageList(): void
    {
        $limit = $this->request->param('limit', 10);
        $res = $this->model->with(['isReadMessage' => function ($query) {
            $query->where(['user_id' => $this->auth->id]);
            return $query;
        }])->where(['status' => PublicStatus::PUBLIC_STATUS_ONE])->paginate($limit)->each(function ($item, $key) {
            $item['is_read'] = !empty($item['isReadMessage']) ? true : false;
            return $item;
        });
        $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }


    //用户是否已读
    public function isRead() : void {
        if ($this->request->isPost()) {
            $message_id = $this->request->param('message_id');
            $message = AppMessage::find($message_id);
            if(empty($message)){
                $this->error('未找到消息');
            }
            $result = false;
            $this->model->startTrans();
            try {
                $is_read = ReadMessage::where(['user_id' => $this->auth->id,'message_id'=>$message_id])->find();
                if(empty($is_read)){
                    // 如果还没有关联数据 则进行新增
                    $result = $message->isReadMessage()->save(['user_id' => $this->auth->id]);
                }
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('成功');
            } else {
                $this->error(('未添加任何行'));
            }
         
        }
        $this->error(('参数错误'));
    }
}